<!-- nbmade-vue3/src/views/iot/nodered/index.vue -->
<template>
  <div class="app-container">
    <el-card>
      <div class="toolbar">
        <el-input v-model="query.flowName" placeholder="Flow名称" style="width: 200px;" />
        <el-button type="primary" style="margin-left:8px" @click="loadData">查询</el-button>
        <el-button type="success" style="margin-left:8px" @click="createNew">新建</el-button>
        <el-button type="warning" style="margin-left:8px" @click="openImportDialog">导入</el-button>
        <el-button type="info" style="margin-left:8px" :disabled="selected.length === 0" @click="exportSelected">导出</el-button>
      </div>
      
      <el-table :data="list" style="width:100%;margin-top:12px" @selection-change="onSelectionChange">
        <el-table-column type="selection" width="48" />
        <el-table-column prop="flowId" label="ID" width="90" />
        <el-table-column prop="flowName" label="Flow名称" width="200" />
        <el-table-column prop="flowDescription" label="描述" width="300" />
        <el-table-column prop="version" label="版本" width="80" />
        <el-table-column prop="isActive" label="激活" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.isActive ? 'success' : 'info'">
              {{ scope.row.isActive ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="isRunning" label="运行状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.isRunning ? 'success' : 'danger'">
              {{ scope.row.isRunning ? '运行中' : '已停止' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300">
          <template #default="scope">
            <el-button link type="primary" @click="openEdit(scope.row)">编辑</el-button>
            <el-button link type="success" @click="deployFlow(scope.row)" v-if="!scope.row.isRunning">部署</el-button>
            <el-button link type="warning" @click="stopFlow(scope.row)" v-if="scope.row.isRunning">停止</el-button>
            <el-button link type="info" @click="exportFlow(scope.row)">导出</el-button>
            <el-button link type="danger" @click="doRemove(scope.row.flowId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <el-pagination
        style="margin-top: 12px;text-align:right;"
        v-model:current-page="pageNum"
        v-model:page-size="pageSize"
        :total="total"
        @current-change="loadData"
        @size-change="loadData"
      />
    </el-card>

    <!-- Flow 编辑对话框 -->
    <el-dialog v-model="visible" title="Flow编辑" width="800px">
      <el-form :model="form" label-width="100px">
        <el-form-item label="Flow名称">
          <el-input v-model="form.flowName" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="form.flowDescription" type="textarea" />
        </el-form-item>
        <el-form-item label="Flow配置">
          <el-input v-model="form.flowConfig" type="textarea" :rows="10" placeholder="JSON格式的Flow配置" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="visible=false">取消</el-button>
        <el-button type="primary" @click="doSave">保存</el-button>
      </template>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog v-model="importVisible" title="导入Flow" width="600px">
      <el-form label-width="100px">
        <el-form-item label="Flow JSON">
          <el-input v-model="importJson" type="textarea" :rows="15" placeholder="粘贴Flow的JSON配置" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="importVisible=false">取消</el-button>
        <el-button type="primary" @click="doImport">导入</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getNodeRedFlows, createNodeRedFlow, updateNodeRedFlow, deleteNodeRedFlow,
  deployFlow as apiDeployFlow, stopFlow as apiStopFlow, exportFlow as apiExportFlow, importFlow as apiImportFlow
} from '@/api/iot/nodered'

const router = useRouter()
const query = ref({ flowName: '' })
const list = ref<any[]>([])
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)

const visible = ref(false)
const importVisible = ref(false)
const form = ref<any>({})
const importJson = ref('')
const selected = ref<any[]>([])
const currentFlowId = ref<number | null>(null)

async function loadData() {
  const { data } = await getNodeRedFlows({ ...query.value, pageNum: pageNum.value, pageSize: pageSize.value })
  list.value = data.records || []
  total.value = data.total || 0
}

function openEdit(row?: any) {
  if (row) {
    // 如果有规则数据，跳转到规则编辑器页面
    router.push({
      path: '/iot/rule-editor',
      query: { flowId: String(row.flowId) }
    })
  } else {
    // 新增规则，打开对话框
    form.value = {}
    visible.value = true
  }
}

function createNew() {
  // 进入空白规则编辑页
  router.push({ path: '/iot/rule-editor' })
}

function openImportDialog() {
  importVisible.value = true
}

function onSelectionChange(rows: any[]) {
  selected.value = rows || []
}

async function exportSelected() {
  if (selected.value.length === 0) return
  // 逐个导出所选规则
  for (const row of selected.value) {
    try {
      const { data } = await apiExportFlow(row.flowId)
      const blob = new Blob([data], { type: 'application/json' })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `${row.flowName}.json`
      a.click()
      URL.revokeObjectURL(url)
    } catch (error) {
      ElMessage.error(`导出失败：${row.flowName}`)
    }
  }
  ElMessage.success(`已导出${selected.value.length}条规则`)
}

async function doSave() {
  if (!form.value.flowName) { ElMessage.error('请填写Flow名称'); return }
  if (form.value.flowId) await updateNodeRedFlow(form.value)
  else await createNodeRedFlow(form.value)
  ElMessage.success('已保存')
  visible.value = false
  loadData()
}

async function deployFlow(row: any) {
  try {
    await apiDeployFlow(row.flowId)
    ElMessage.success('Flow部署成功')
    loadData()
  } catch (error) {
    ElMessage.error('Flow部署失败')
  }
}

async function stopFlow(row: any) {
  try {
    await apiStopFlow(row.flowId)
    ElMessage.success('Flow已停止')
    loadData()
  } catch (error) {
    ElMessage.error('停止Flow失败')
  }
}

async function exportFlow(row: any) {
  try {
    const { data } = await apiExportFlow(row.flowId)
    // 创建下载链接
    const blob = new Blob([data], { type: 'application/json' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `${row.flowName}.json`
    a.click()
    URL.revokeObjectURL(url)
    ElMessage.success('Flow导出成功')
  } catch (error) {
    ElMessage.error('Flow导出失败')
  }
}

// removed openEditor button and handler

async function doImport() {
  if (!importJson.value) { ElMessage.error('请输入Flow JSON'); return }
  try {
    await apiImportFlow(importJson.value)
    ElMessage.success('Flow导入成功')
    importVisible.value = false
    importJson.value = ''
    loadData()
  } catch (error) {
    ElMessage.error('Flow导入失败')
  }
}

async function doRemove(id: number) {
  await ElMessageBox.confirm('确认删除该Flow吗？', '提示')
  await deleteNodeRedFlow(id)
  ElMessage.success('已删除')
  loadData()
}

loadData()
</script>